//
//  DSSHSearchDVC.m
//  DSSH
//
//  Created by Fuhao on 16/4/14.
//  Copyright © 2016年 lcy. All rights reserved.
//

#import "DSSHSearchDVC.h"
#import "SelectButtonM.h"
#import "DSSHTaskPhontoVcC.h"
#define BUTTONSB 10
#define COL 3
#define BUTTONH 30
#define BUTTONw (ZYAppWidth - 60)/3
@interface DSSHSearchDVC ()<UITextFieldDelegate>
{
    UIView * _searchV ;
    NSMutableArray *_dataArr;
    NSMutableArray *_dataAfsea;
    BOOL   _isFrist;
    NSString       *_Frristletter;
    CGFloat _hightofV;
    UIScrollView * _backScroll;
    UIView *_lastview;
    
    
}

@end

@implementation DSSHSearchDVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _isFrist =YES;
    _dataAfsea = [NSMutableArray array];
    _dataArr = [NSMutableArray array];
    self.view.backgroundColor = BACKGROUNDGARY;
    _backScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ZYAppWidth, ZYAppHeight - 64 - 49)];
    _backScroll.backgroundColor = BACKGROUNDGARY;
    
    [self.view addSubview:_backScroll];
    //创建背景的scroll
    
    [_backScroll addSubview:_searchV];
    
    //设置左边按钮显示的内容
    UIButton *leftbutton = [[UIButton alloc] init];
    [leftbutton setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [leftbutton addTarget:self action:@selector(Hitleftbutton) forControlEvents:UIControlEventTouchUpInside];
    leftbutton.frame = CGRectMake(0, 0, 20, 20);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    
    //数据加载
    NSArray *arrydata = @[@{@"Distrct":@"A",@"Detail":@[@"阿里巴巴",@"安1区",@"昂2区",@"锕锕锕锕"]},
                  @{@"Distrct":@"B",@"Detail":@[@"北京一号",@"北极"]},
                  @{@"Distrct":@"E",@"Detail":@[@"俄怀明",@"俄罗斯"]},
                 @{@"Distrct":@"F",@"Detail":@[@"f1",@"f1",@"f1",@"f1",@"f1",@"f1"]}
                  ];
    for (NSDictionary *dict in arrydata) {
        [_dataArr addObject:[SelectButtonM SelectwithDict:dict]];
    }
    self.navigationItem.titleView = [self createseachview];
    
    //根据数据来绘制视图
    [self createsbuttons:_dataArr];
    // Do any additional setup after loading the view.
}
//创建搜索栏框
-(UIView *)createseachview
{
        UIView *Mview = [[UIView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width-100,30)];
        Mview.backgroundColor = [UIColor whiteColor];
        Mview.layer.cornerRadius = 5;
        
        UIImageView *imageview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"fangdajing"]];
        [Mview addSubview:imageview];
        [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(@20);
            make.centerY.equalTo(Mview.mas_centerY);
            make.left.equalTo(Mview.mas_left).with.offset(5);
        }];
        UITextField *textfield = [[UITextField alloc] init];
        [Mview addSubview:textfield];
        textfield.delegate = self;
        textfield.font = [UIFont systemFontOfSize:13.0];
        textfield.placeholder = @"搜索相关内容";
        [textfield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(imageview.mas_right).with.offset(0);
            make.centerY.equalTo(Mview.mas_centerY);
            make.height.equalTo(@30);
            make.right.equalTo(Mview.mas_right).with.offset(0);
        }];
        return Mview;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
#pragma mark 字符和视图处理的函数
//当点击时模仿reload
-(void)createsbuttons:(NSMutableArray *)dataarr
{
    for (int i = 0; i <dataarr.count; i++) {
        [self createDbuttons:dataarr[i]];
    }
}
//创建数据按钮
-(void)createDbuttons:(SelectButtonM *)sel
{
    int buttonsnum = (int)sel.Detail.count;
    UITextField *Dtext = [[UITextField alloc] initWithFrame:CGRectMake(0, _hightofV, ZYAppWidth,25)];
    Dtext.backgroundColor = BACKGROUNDGARY;
    Dtext.text = sel.Distrct;
    Dtext.userInteractionEnabled = NO;
    [_backScroll addSubview:Dtext];
    
    
    
    //添加buttons获取button的行数
    UIView *views = [[UIView alloc ]initWithFrame:CGRectMake(0, _hightofV + 25, ZYAppWidth,(buttonsnum%3==0 ? (buttonsnum/3):( buttonsnum/3+1) )*(BUTTONH + BUTTONSB*2))];
    [views setBackgroundColor:[UIColor whiteColor]];
    [_backScroll addSubview:views];
    _lastview = views;
    for(int i = 0 ; i < buttonsnum ;i++)
    {
        int col = i % COL;
        int row = i / COL;
        UIButton *button = [[UIButton alloc] init];
        [views addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(views.mas_top).with.offset(10+row * (BUTTONH +20));
            make.left.equalTo(views.mas_left).with.offset(10+col *(BUTTONw+20));
            make.width.mas_equalTo(BUTTONw);
            make.height.mas_equalTo(BUTTONH);
        }];
        button.layer.cornerRadius = 5;
        button.backgroundColor = BACKGROUNDGARY;
        [button setTitle: sel.Detail[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(hitbutton:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    _hightofV = CGRectGetMaxY(_lastview.frame);
    _backScroll.contentSize = CGSizeMake(0, _hightofV);
    
}
-(void)DoDataArr: (NSString *)string
{
    NSString * distrct = nil;
    
    if(_dataAfsea.count != 0)
    {
        SelectButtonM *sb = _dataAfsea[0];
        NSMutableArray *new = [NSMutableArray array];
        for (NSString *str in sb.Detail) {
            if([str rangeOfString:string].length)
            {
                [new addObject:str];
            }
        }
        sb.Detail = new;
        
        
    }
    else{
        for (SelectButtonM *sel in _dataArr) {
                //防止_dataarr被修改
                distrct = sel.Distrct;
                if(*distrct.cString == (*_Frristletter.cString -32) )
                {
                    SelectButtonM *sel1 = [[SelectButtonM alloc]init];
                    sel1.Distrct = sel.Distrct;
                    sel1.Detail = sel.Detail;
                    [ _dataAfsea addObject:sel1];
                    break;
            }
        }
    }
}
-(void)Hitleftbutton
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)hitbutton:(UIButton *)button{
    DSSHLog(@"%@被点击",button.titleLabel.text);
    DSSHTaskPhontoVcC *vc = [[DSSHTaskPhontoVcC alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    //移除所有的button并重新绘图
}
-(void)removeallbuttons
{
    for (UIView *viewb in _backScroll.subviews) {
        [viewb removeFromSuperview];
        [viewb setNeedsDisplay];
    }
    _hightofV = 0;
}
#pragma mark TextFild`s delegate
//获取首字母对应的地区编号（只对首字母有效）
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(_isFrist)
    {
        DSSHLog(@"%@",string);
        _isFrist = NO;
        _Frristletter = string;

        //根据输入的类容对数据进行筛选
        [self DoDataArr:string];
        [self removeallbuttons];
        [self createsbuttons:_dataAfsea];
    }
    DSSHLog(@"%ld",[textField.text lengthOfBytesUsingEncoding:NSUTF8StringEncoding ]);
    if([string isEqualToString:@""] && ([textField.text lengthOfBytesUsingEncoding:NSUTF8StringEncoding] ==1 || [textField.text lengthOfBytesUsingEncoding:NSUTF8StringEncoding ]==3))
    {
        
        _isFrist = YES;
        [self removeallbuttons];
        [_dataAfsea removeAllObjects];
        [self createsbuttons:_dataArr];
        
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    
    //进行搜索
    
    
    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    //根据输入的类容对数据进行筛选
    if(_Frristletter != nil )
    {
        [self removeallbuttons];
        [self DoDataArr:textField.text];
        [self createsbuttons: _dataAfsea];
    }
    
    _isFrist = YES;
    DSSHLog(@"%@",textField.text);
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
